﻿#region References
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using System.Windows.Forms;
using System.Security.Cryptography;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using System.Data;
using CdcSoftware.Pivotal.Engine.Types.Database;
using CdcSoftware.Pivotal.Engine.Types.MailMerges;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Types.DataTemplates;
#endregion

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Cashier_Log : FormClientTask
    {
        #region Private Variables.

        private bool m_LoginStaffCode = false;

        private System.Windows.Forms.TextBox txtCurrentPassword, txtNewPassword, txtConfirmPassword;
        private System.Windows.Forms.Button btnOk, btnCancel;
        private System.Windows.Forms.Label lblCurrentPassword, lblNewPassword, lblConfirmPassword;

        private Form popupChangePassword = null;
        private Form popupAuthorization = null;
        private bool changePassword = false;
        private bool clockOut = false;
        private DataRow[] loggedInCashier = null;
        #endregion

        /// <summary>
        /// This event fires on exit of staff code field. On exit check the staff code and the fill in the corresponding staff id. If none found, then prompt the user.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-09-06      DS          Initial version for Retail.
        /// </history>
        public virtual void OnExitStaffCode(object sender, EventArgs args)
        {
            try
            {
                if (Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Code"]) || this.PrimaryDataRow["Login_Staff_Code"] == null)
                {
                    this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
                    EnableDisableButtons();
                    return;
                }

                DataTable staff = Globals.GetDataTable("RE_Active Staff with Staff Code?", new object[] { this.PrimaryDataRow["Login_Staff_Code"].ToString() },
                    new string[] { "RE_Staff_Id", "Cashier" });
                if (staff != null && staff.Rows.Count == 1)
                {
                    //DS: Check if the staff can login as Cashier or not.
                    if (TypeConvert.ToBoolean(staff.Rows[0]["Cashier"]))
                    {
                        this.PrimaryDataRow["Login_Staff_Id"] = staff.Rows[0]["RE_Staff_Id"];
                        EnableDisableButtons();
                        return;
                    }
                    else
                        PivotalMessageBox.Show("Staff is not allowed to login as Cashier.", MessageBoxButtons.OK, MessageBoxIcon.Error);    
                }
                else if (staff != null && staff.Rows.Count > 1)
                {
                    PivotalMessageBox.Show("Multiple Staff found for the code entered: " + this.PrimaryDataRow["Login_Staff_Code"].ToString() +
                        "\r\nPlease contact system Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Warning);                    
                }
                else
                {
                    PivotalMessageBox.Show("No Staff found for the code entered: " + this.PrimaryDataRow["Login_Staff_Code"].ToString() + "\r\nPlease enter a valid code.",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
                this.PrimaryDataRow["Login_Staff_Code"] = DBNull.Value;

                EnableDisableButtons();
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On Enter press on field LoginStaffCode move to the Clock-in button if valid staff_code is entered.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.10.3     2012-03-26     NN          Initial version for Retail.
        /// </history>
        public virtual void OnKeyEnterStaffCode(object sender, KeyEventArgs args)
        {
            try
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.FormControl.GetControlByDataName("Login_Staff_Id").Focus();
                    if(Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]))
                        this.FormControl.GetControlByDataName("Login_Staff_Code").Focus();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Enable/Disable the buttons Clock-In and Clock-Out.
        /// </summary>
        private void EnableDisableButtons()
        {
            if (!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]))
            {
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = true;
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = true;
                this.FormControl.GetControlByName("PivBtnClockIn").Focus();
            }
            else
            {
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = false;
                ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = false;
                this.FormControl.GetControlByDataName("Login_Staff_Code").Focus();
            }
        }

        /// <summary>
        /// On click of Clock-In button.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-09-06      DS          Initial version for Retail.
        /// </history>
        public virtual void OnClickClockIn(object sender, EventArgs args)
        {
            clockOut = false;
            loggedInCashier = null;
            try
            {
                bool mobileuser = false;
                bool masterPOS = false;

                mobileuser = this.SystemClient.SystemInformation.IsMobile;

                //RA:16/Aug/2012:Change for Mobile System:Start:
                Id storePOSId = Id.Create(Globals.ServerSqlIndex("Employee", "RE_Store_POS_Id", this.SystemClient.UserProfile.EmployeeId));

                if (storePOSId != null)
                {
                    masterPOS = TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Store_POS", "Master_POS", storePOSId));
                }

                if ((!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"])) || (mobileuser && !masterPOS))
                {
                    DataTable cashierLogin = Globals.GetDataTable("RE_All Cashier Logins for Today", null, new string[] { "Staff_Id", "Staff_Code", "End_Time",
                        "Store_Id", "POS_Id" });                    
                    //Check in the staff login secondary for the day, if the user is already logged in (row exists for the staff where out time is null) (all records across all stores)
                    int count = cashierLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                        && Convert.IsDBNull(a["End_Time"]));

                    if (count > 0)
                    {
                        //User is already logged-in.
                        PivotalMessageBox.Show("There is already a login for the staff at the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {                        
                        //check if the POS selected is already selected for another staff (row exists for the same POS with a different staff where out time is null)
                        int cashierCount = cashierLogin.AsEnumerable().Count(a => Id.Create(a["Store_Id"]) == Id.Create(this.PrimaryDataRow["Store_Id"]) &&
                            Id.Create(a["POS_Id"]) == Id.Create(this.PrimaryDataRow["Login_POS_Id"]) && Convert.IsDBNull(a["End_Time"]));
                        if (cashierCount > 0)
                        {
                            //The POS is already in use by a different cashier.
                            PivotalMessageBox.Show("The POS is already in use by a different cashier.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                            //Refresh the bottom status strip text.
                            Globals.SetCashierStatusStrip(Globals.StatusStripPane.EnvironmentPane);
                        }
                        else
                        {                            
                            //Check if the Staff trying to login as Cashier is logged in as staff or not. If not then prompt saying to login as staff first before logging in as Cashier.
                            DataTable staffLogin = Globals.GetDataTable("RE_All Staff Logins for Today with Store?", new object[] { this.PrimaryDataRow["Store_Id"] },
                                new string[] { "Staff_Id", "Out_Time" });

                            int staffCount = staffLogin.AsEnumerable().Count(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                && Convert.IsDBNull(a["Out_Time"]));

                            if (staffCount > 0 || ((mobileuser && !masterPOS)))
                            {                                
                                //Check if for the selected staff, the Prompt_To_Change field is set to true.
                                if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["Login_Staff_Id"]))))
                                    ShowChangePasswordPopup();
                                else
                                    ShowAuthorizationPopup();
                            }
                            else
                            {
                                //Prompt the staff saying to login as staff first before logging in as Cashier.
                                PivotalMessageBox.Show("Please login as staff before logging into a POS as cashier.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }
                }
                else
                {
                    if (Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                    {
                        PivotalMessageBox.Show("Create a batch for the store before logging-in.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    PivotalMessageBox.Show("Please fill all the required fields marked with '*'.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// On click of Clock-Out button.
        /// </summary>
        /// <param name="sender">The control associated with the event triggered</param>
        /// <param name="args">The argument for the event</param>
        /// <history>
        /// #Revision   Date            Author      Description
        /// 6.0.8.1     2011-09-06      DS          Initial version for Retail.
        /// </history>
        public virtual void OnClickClockOut(object sender, EventArgs args)
        {
            clockOut = true;
            loggedInCashier = null;

            bool mobileuser = false;
            bool masterPOS = false;
            try
            {
            mobileuser = this.SystemClient.SystemInformation.IsMobile;

            //RA:16/Aug/2012:Change for Mobile System:Start:
            Id storePOSId = Id.Create(Globals.ServerSqlIndex("Employee", "RE_Store_POS_Id", this.SystemClient.UserProfile.EmployeeId));

            if (storePOSId != null)
            {
                masterPOS = TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Store_POS", "Master_POS", storePOSId));
            }
            if ((!Convert.IsDBNull(this.PrimaryDataRow["Login_Staff_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"])) || (mobileuser && !masterPOS))
            {
                DataTable cashierLogin = Globals.GetDataTable("RE_All Cashier Logins for Today", null, new string[] { "Staff_Id", "Staff_Code", "End_Time", "Store_Id", "POS_Id" });

                loggedInCashier = cashierLogin.AsEnumerable().Where(a => Id.Create(a["Staff_Id"]) == Id.Create(this.PrimaryDataRow["Login_Staff_Id"])
                                       && Convert.IsDBNull(a["End_Time"])).ToArray();

                if (loggedInCashier.Count() == 1)
                {
                    if (Id.Create(loggedInCashier[0]["POS_Id"]) != Id.Create(this.PrimaryDataRow["Login_POS_Id"]))
                    {
                        PivotalMessageBox.Show("You should logout from the same POS from which you have logged in.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    //Check if for the selected staff, the Prompt_To_Change field is set to true.
                    if (TypeConvert.ToBoolean(Globals.ServerSqlIndex("RE_Staff", "Prompt_To_Reset", Id.Create(this.PrimaryDataRow["Login_Staff_Id"]))))
                        ShowChangePasswordPopup();
                    else
                        ShowAuthorizationPopup();
                }
                else if (loggedInCashier.Count() > 1)
                    PivotalMessageBox.Show("Multiple entry exists for the user. Please contact Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    PivotalMessageBox.Show("No entry for the user to clock-out.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (Convert.IsDBNull(this.PrimaryDataRow["Login_Batch_Id"]))
                {
                    PivotalMessageBox.Show("The Batch is already closed for the Day.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                PivotalMessageBox.Show("Please fill all the required fields marked with '*'.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowChangePasswordPopup()
        {
            changePassword = true;
            popupChangePassword = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.txtNewPassword = new System.Windows.Forms.TextBox();
            this.txtConfirmPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            this.lblNewPassword = new System.Windows.Forms.Label();
            this.lblConfirmPassword = new System.Windows.Forms.Label();
            popupChangePassword.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 0;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // txtNewPassword
            // 
            this.txtNewPassword.Location = new System.Drawing.Point(181, 71);
            this.txtNewPassword.Name = "txtNewPassword";
            this.txtNewPassword.Size = new System.Drawing.Size(109, 20);
            this.txtNewPassword.TabIndex = 1;
            this.txtNewPassword.UseSystemPasswordChar = true;
            // 
            // txtConfirmPassword
            // 
            this.txtConfirmPassword.Location = new System.Drawing.Point(181, 112);
            this.txtConfirmPassword.Name = "txtNewPassword";
            this.txtConfirmPassword.Size = new System.Drawing.Size(109, 20);
            this.txtConfirmPassword.TabIndex = 2;
            this.txtConfirmPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 161);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 3;
            this.btnOk.Text = "Ok";
            this.btnOk.BringToFront();
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 161);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 4;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Current Password:";
            // 
            // lblNewPassword
            // 
            this.lblNewPassword.AutoSize = true;
            this.lblNewPassword.Location = new System.Drawing.Point(43, 74);
            this.lblNewPassword.Name = "lblNewPassword";
            this.lblNewPassword.Size = new System.Drawing.Size(138, 15);
            this.lblNewPassword.TabIndex = 5;
            this.lblNewPassword.Text = "New Password:";
            // 
            // lblConfirmPassword
            // 
            this.lblConfirmPassword.AutoSize = true;
            this.lblConfirmPassword.Location = new System.Drawing.Point(43, 115);
            this.lblConfirmPassword.Name = "lblConfirmPassword";
            this.lblConfirmPassword.Size = new System.Drawing.Size(138, 15);
            this.lblConfirmPassword.TabIndex = 6;
            this.lblConfirmPassword.Text = "Confirm Password:";
            // 
            // Form1
            // 
            popupChangePassword.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupChangePassword.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupChangePassword.AcceptButton = this.btnOk;
            popupChangePassword.CancelButton = this.btnCancel;
            popupChangePassword.ClientSize = new System.Drawing.Size(348, 224);
            popupChangePassword.StartPosition = FormStartPosition.CenterScreen;
            popupChangePassword.Controls.Add(this.lblCurrentPassword);
            popupChangePassword.Controls.Add(this.lblNewPassword);
            popupChangePassword.Controls.Add(this.lblConfirmPassword);
            popupChangePassword.Controls.Add(this.btnOk);
            popupChangePassword.Controls.Add(this.btnCancel);
            popupChangePassword.Controls.Add(this.txtCurrentPassword);
            popupChangePassword.Controls.Add(this.txtNewPassword);
            popupChangePassword.Controls.Add(this.txtConfirmPassword);
            popupChangePassword.Name = "popupChangePassword";
            popupChangePassword.Text = "Change Password";
            popupChangePassword.ResumeLayout(false);
            popupChangePassword.PerformLayout();
            popupChangePassword.ShowDialog();
        }

        /// <summary>
        /// Show the authorization Pop-up.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void ShowAuthorizationPopup()
        {
            changePassword = false;
            popupAuthorization = new Form();

            this.txtCurrentPassword = new System.Windows.Forms.TextBox();
            this.btnOk = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.lblCurrentPassword = new System.Windows.Forms.Label();
            popupAuthorization.SuspendLayout();
            // 
            // txtCurrentPassword
            // 
            this.txtCurrentPassword.Location = new System.Drawing.Point(181, 30);
            this.txtCurrentPassword.Name = "txtCurrentPassword";
            this.txtCurrentPassword.Size = new System.Drawing.Size(109, 20);
            this.txtCurrentPassword.TabIndex = 1;
            this.txtCurrentPassword.UseSystemPasswordChar = true;
            // 
            // btnOk
            // 
            this.btnOk.Location = new System.Drawing.Point(134, 80);
            this.btnOk.Name = "Ok";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 2;
            this.btnOk.Text = "Ok";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.Ok_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Location = new System.Drawing.Point(215, 80);
            this.btnCancel.Name = "Cancel";
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.TabIndex = 3;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // lblCurrentPassword
            // 
            this.lblCurrentPassword.AutoSize = true;
            this.lblCurrentPassword.Location = new System.Drawing.Point(43, 33);
            this.lblCurrentPassword.Name = "lblCurrentPassword";
            this.lblCurrentPassword.Size = new System.Drawing.Size(138, 15);
            this.lblCurrentPassword.TabIndex = 5;
            this.lblCurrentPassword.Text = "Password:";
            // 
            // Form1
            // 
            popupAuthorization.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            popupAuthorization.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            popupAuthorization.AcceptButton = this.btnOk;
            popupAuthorization.CancelButton = this.btnCancel;
            popupAuthorization.ClientSize = new System.Drawing.Size(348, 133);
            popupAuthorization.StartPosition = FormStartPosition.CenterScreen;
            popupAuthorization.Controls.Add(this.lblCurrentPassword);
            popupAuthorization.Controls.Add(this.btnOk);
            popupAuthorization.Controls.Add(this.btnCancel);
            popupAuthorization.Controls.Add(this.txtCurrentPassword);
            popupAuthorization.Name = "popupAuthorization";
            popupAuthorization.Text = "Enter Password";
            popupAuthorization.ResumeLayout(false);
            popupAuthorization.PerformLayout();
            popupAuthorization.ShowDialog();
        }

        /// <summary>
        /// Event handler for the OK click of the popup pwd challenge.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void Ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (changePassword)
                {
                    //Verify the current password is correct and the new password matches the confirm password fields.
                    //Update the new password in the staff table and clear the Prompt_To_Change field and Clock-In the staff.

                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty || txtNewPassword.Text.Trim() == string.Empty || txtConfirmPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Login_Staff_Id"])));
                    //Match the old password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //If new password and the confirm password does not match prompt the user with error.
                        if (!String.Equals(txtNewPassword.Text, txtConfirmPassword.Text))
                        {
                            PivotalMessageBox.Show("Password confirmation failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.txtNewPassword.Text = string.Empty;
                            this.txtConfirmPassword.Text = string.Empty;
                            this.txtNewPassword.Focus();
                            return;
                        }

                        //Now change the password for the Staff and set the field Prompt_To_Reset to false.
                        this.SystemClient.ExecuteServerTask("RE_Store", "SetStaffPassword", new Type[] { typeof(Id), typeof(string) },
                            new object[] { Id.Create(this.PrimaryDataRow["Login_Staff_Id"]), Globals.Encrypt(this.txtNewPassword.Text) });

                        //After successful validation and password change, close the pop-up.
                        popupChangePassword.Close();

                        //Clock-In or Clock-Out the staff.
                        if (!clockOut)
                            ClockInCashier();
                        else
                            ClockOutCashier();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Current Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtNewPassword.Text = string.Empty;
                        this.txtConfirmPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                }
                else
                {
                    //Verify the current password is correct and clock in the staff.
                    //User selects OK but value not provided.
                    if (txtCurrentPassword.Text.Trim() == string.Empty)
                    {
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }

                    string password = TypeConvert.ToString(Globals.ServerSqlIndex("RE_Staff", "Password_", Id.Create(this.PrimaryDataRow["Login_Staff_Id"])));
                    //Match the password with the DB value. If matched go ahead, esle prompt the user.
                    if (String.Equals(Globals.Decrypt(password), txtCurrentPassword.Text))
                    {
                        //After successful validation and password change, close the pop-up.
                        popupAuthorization.Close();
                    }
                    else
                    {
                        PivotalMessageBox.Show("Password verification failed. Please enter again.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCurrentPassword.Text = string.Empty;
                        this.txtCurrentPassword.Focus();
                        return;
                    }
                    //Clock-In or Clock-Out the staff.
                    if (!clockOut)
                        ClockInCashier();
                    else
                        ClockOutCashier();
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Add a new row in the secondary staff login:
        ///•	Staff_Code = Staff Code entered above
        ///•	Staff_Id =  staff_Id retrieved above
        ///•	Store_Id =  current store
        ///•	Role =  Role selected above
        ///•	Login_Date =  Current Date
        ///•	In_Time = Current Time
        ///If the role is In Charge, update the In_Charge_Id field with the selected staff_id  for all the POS records for that store.
        ///Ensure that the staff id selected has the In_Charge flag set to true.
        ///Clear all the primary input fields.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void ClockInCashier()
        {
            this.SystemClient.ExecuteServerTask("RE_Store", "ClockInCashier", new Type[] { typeof(string), typeof(object), typeof(object), typeof(object), typeof(object) },
                new object[] { this.PrimaryDataRow["Login_Staff_Code"].ToString(), this.PrimaryDataRow["Login_Staff_Id"], this.PrimaryDataRow["Store_Id"], 
                    this.PrimaryDataRow["Login_POS_Id"], this.PrimaryDataRow["Login_Batch_Id"] });

            //Refresh the grid data.
            PivotalSearchResultsGrid cashierLoginGrid = (PivotalSearchResultsGrid)this.FormControl.GetControlByName("CashierLoginGrid");
            cashierLoginGrid.RefreshGridData();

            //Clears all the primary fields.
            ClearPrimaryFields();

            //Set the bottom status strip text.
            Globals.SetCashierStatusStrip(Globals.StatusStripPane.EnvironmentPane);

            this.FormView.CloseForm(true);

            //DS: 19042013 - For Offline if the POS is not master POS, then don't allow to create new Sale.
            if (SystemClient.SystemInformation.IsMobile && !Globals.IsMasterPOS)
                PivotalMessageBox.Show("New Sale is not available Offline when POS is not Master POS.", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                Globals.ShowForm("RE_Sale – Walk In", null, null, ActionTargetWindow.Popup);
        }

        /// <summary>
        /// Update the logged-in row in the secondary staff login:
        ///•	Out_Time = Current Time
        ///If the role is In Charge, update the In_Charge_Id field with the selected staff_id  for all the POS records for that store.
        ///Ensure that the staff id selected has the In_Charge flag set to true.
        ///Clear all the primary input fields.
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void ClockOutCashier()
        {
            this.SystemClient.ExecuteServerTask("RE_Store", "ClockOutCashier", new Type[] { typeof(Id), typeof(object), typeof(object) },
                new object[] { Id.Create(loggedInCashier[0]["RE_Cashier_Log_Id"]), this.PrimaryDataRow["Store_Id"], this.PrimaryDataRow["Login_POS_Id"] });

            //Refresh the grid data.
            PivotalSearchResultsGrid cashierLoginGrid = (PivotalSearchResultsGrid)this.FormControl.GetControlByName("CashierLoginGrid");
            cashierLoginGrid.RefreshGridData();

            //Clears all the primary fields.
            ClearPrimaryFields();

            //Set the bottom status strip text.
            Globals.SetCashierStatusStrip(Globals.StatusStripPane.EnvironmentPane);
        }

        /// <summary>
        /// Clears all the primary fields.
        /// </summary>
        /// 
        /// <history>
        /// Revision#      Date            Author          Description
        /// 6.0.8.1        2011-09-06      DS              Initial version for Retail.                                                
        /// </history>
        private void ClearPrimaryFields()
        {
            //this.PrimaryDataRow["Login_Batch_Id"] = DBNull.Value;
            this.PrimaryDataRow["Login_Staff_Code"] = DBNull.Value;
            this.PrimaryDataRow["Login_Staff_Id"] = DBNull.Value;
            ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockIn")).Enabled = false;
            ((PivotalButton)this.FormControl.GetControlByName("PivBtnClockOut")).Enabled = false;
        }
    }
}
